package com.study.web.mzt.nv.bean.thread;

import com.study.web.mzt.nv.bean.NsSingle;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * @author study
 * @version 1.0
 * @date 2020/8/9 10:09
 */
@Slf4j
public class NsRunnable implements Runnable {
    private NsSingle nsSingle;
    private String savePath;

    public NsRunnable(NsSingle nsSingle, String savePath) {
        this.nsSingle = nsSingle;
        this.savePath = savePath;
    }

    @Override
    public void run() {
        if (Objects.isNull(nsSingle)) {
            return;
        }

        for (Integer i = 1; i < nsSingle.getNum(); i++) {
            try {
                String downUrl = String.format(nsSingle.getPicUrl(), i);
                Connection.Response response = Jsoup.connect(downUrl)
                        .referrer(nsSingle.getPageUrl())
                        .ignoreContentType(Boolean.TRUE).execute();
                BufferedInputStream inputStream = response.bodyStream();
                String basePath = StringUtils.join(new String[]{savePath, nsSingle.getSavePath()}, "/");
                FileUtils.copyInputStreamToFile(inputStream, Paths.get(basePath, i + nsSingle.getExtName()).toFile());
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                log.error("下载失败{}", nsSingle.toString());
            }
        }

    }
}
